package org.onvivals.app.ai.tts.model.volcengine;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.onvivals.app.ai.tts.AbstractTtsService;
import org.onvivals.common.utils.FFmpegUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * VolcengineTtsService
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
public class VolcengineTtsService extends AbstractTtsService {

    private static final Lock lock = new ReentrantLock();
    private static StringBuffer fileUrl = new StringBuffer();

    private JSONObject ttsConfig;

    public VolcengineTtsService(JSONObject config) {
        this.ttsConfig = config;
    }

    public VolcengineTtsService() {

    }

    public static String generateFilePath() {
        lock.lock();
        try {
            String tmpDir = System.getProperty("java.io.tmpdir");
            String uniqueId = IdUtil.getSnowflakeNextIdStr();
            return tmpDir + uniqueId + ".mp3";
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Optional<String> speechSynthesizer(String id, String content) {
        lock.lock();
        try {
            String filePath = generateFilePath();
            String appId = ttsConfig.getStr("app_id");
            String clusterId = ttsConfig.getStr("cluster_id");
            String accessToken = ttsConfig.getStr("access_token");
            String voiceType = ttsConfig.getStr("voice_type");
            VolcengineCompletionResponse completionResponse = new VolcengineCompletionResponse();
            VolcengineCompletionResponse.App app = new VolcengineCompletionResponse.App(appId, accessToken, clusterId);
            VolcengineCompletionResponse.User user = new VolcengineCompletionResponse.User(id);
            VolcengineCompletionResponse.Audio audio = new VolcengineCompletionResponse.Audio(voiceType, "mp3", 1, 1.0, 1.0, 1.0, "happy", "cn", 16000);
            VolcengineCompletionResponse.Request request = new VolcengineCompletionResponse.Request(UUID.fastUUID().toString(), content, "plain", "query");
            completionResponse.setApp(app);
            completionResponse.setUser(user);
            completionResponse.setAudio(audio);
            completionResponse.setRequest(request);
            HttpResponse response = HttpUtil.createPost("https://openspeech.bytedance.com/api/v1/tts")
                    .header("Authorization", "Bearer; " + accessToken)
                    .body(JSONUtil.toJsonStr(completionResponse))
                    .execute();
            if (response.isOk()) {
                JSONObject result = JSONUtil.parseObj(response.body());
                String data = result.getStr("data");
                byte[] decode = Base64.decode(data);
                File f = new File(filePath);
                FileUtil.writeBytes(decode, f);
                String newFilePath = generateFilePath();
                FFmpegUtils.waveMaker(f.getAbsolutePath(), newFilePath);
                f.delete();
                return Optional.of(newFilePath);
            }
        } finally {
            lock.unlock();
        }
        return Optional.empty();
    }
}
